package com.yt.sys.common.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 支付宝配置类
 */
@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayConfig {
    /**
     * 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
     */
    private String appId;

    /**
     * 应用私钥，就是工具生成的应用私钥
     */
    private String merchantPrivateKey;
    
    /**
     * 支付宝公钥,对应APPID下的支付宝公钥。
     */
    private String alipayPublicKey;

    /**
     * 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
     */
    private String notifyUrl;
    
    /**
     * 同步通知，支付成功，一般跳转到成功页
     */
    private String returnUrl;

    /**
     * 签名方式
     */
    private String signType;

    /**
     * 字符编码格式
     */
    private String charset;

    /**
     * 订单超时时间
     */
    private String timeout = "30m";

    /**
     * 支付宝网关；https://openapi-sandbox.dl.alipaydev.com/gateway.do
     */
    private String gatewayUrl;

    /**
     * 发起支付请求
     *
     * @param outTradeNo  商户订单号
     * @param totalAmount 订单总金额
     * @param subject     订单标题
     * @param body        订单描述
     * @return 支付页面表单
     * @throws AlipayApiException 支付宝API异常
     */
    public String pay(String outTradeNo, String totalAmount, String subject, String body) throws AlipayApiException {
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, merchantPrivateKey,
                "json", charset, alipayPublicKey, signType);

        //2、创建一个支付请求，并设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        alipayRequest.setBizContent(" {\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"total_amount\":\"" + totalAmount + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"body\":\"" + body + "\"," +
                "\"timeout_express\":\"" + timeout + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
                
        String result = alipayClient.pageExecute(alipayRequest, "POST").getBody();
        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);
        return result;
    }
}